// Copyright (C) 2023 即时通讯网(52im.net) & Jack Jiang.
// The RainbowChat Project. All rights reserved.
// 
// 【本产品为著作权产品，合法授权后请放心使用，禁止外传！】
// 【本次授权给：<北京小羊驼科技有限公司>，授权编号：<NT231212144350>，代码指纹：<A.702363430.550>，技术对接人微信：<ID: wxid_wbyootvkdcgj22>】
// 【授权寄送：<收件：苏先生、地址：北京市大兴区北京密码西区6号楼1单元301、电话：18613885610、邮箱：bd@huiyuanxiang-inc.com>】
// 
// 【本系列产品在国家版权局的著作权登记信息如下】：
// 1）国家版权局登记名(简称)和权证号：RainbowChat    （证书号：软著登字第1220494号、登记号：2016SR041877）
// 2）国家版权局登记名(简称)和权证号：RainbowChat-Web（证书号：软著登字第3743440号、登记号：2019SR0322683）
// 3）国家版权局登记名(简称)和权证号：RainbowAV      （证书号：软著登字第2262004号、登记号：2017SR676720）
// 4）国家版权局登记名(简称)和权证号：MobileIMSDK-Web（证书号：软著登字第2262073号、登记号：2017SR676789）
// 5）国家版权局登记名(简称)和权证号：MobileIMSDK    （证书号：软著登字第1220581号、登记号：2016SR041964）
// * 著作权所有人：江顺/苏州网际时代信息科技有限公司
// 
// 【违法或违规使用投诉和举报方式】：
// 联系邮件：jack.jiang@52im.net
// 联系微信：hellojackjiang
// 联系QQ号：413980957
// 授权说明：http://www.52im.net/thread-1115-1-1.html
// 官方社区：http://www.52im.net
package com.x52im.rbchat.logic.more;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

import com.eva.android.widget.BaseActivity;
import com.eva.android.widget.WidgetUtils;
import com.eva.android.x.XToolKits;
import com.x52im.rbchat.R;
import com.x52im.rbchat.utils.IntentFactory;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

/**
 * 帮助页面。
 *
 * @author Jason Li
 * @since 2.0
 */
public class HelpActivity extends BaseActivity implements ViewPager.OnPageChangeListener, OnTouchListener, OnGestureListener
{
	public final static int FININSH_VIEWPAGE_FINISHACTIVITY = 0;
	public final static int FININSH_VIEWPAGE_GO_TAB_HOST = 1;
	public final static String BUNDLE_LISTER = "finishLinster";
	
	private GestureDetector mGestureDetector;
	private ViewPager vp;
	// [FIX BUG]：[bug]5、【重要】解决了帮助页面的内存泄漏问题（内存泄漏高达15M）。
	// 		内存泄漏的原因是：该Activity中错误地adaptery设置成了static类型，从而导致该adapter引
	// 		用的activity(context)无法被释放，进而该Activity所占用的15M内存将直致程序退出才能释放的严重泄漏问题。
	private ViewPagerAdapter vpAdapter;
	private List<View> views;
	//引导页合集
	private int[] pageImages = new int[] { R.drawable.help_one, R.drawable.help_two, R.drawable.help_three};
	//帮助页面合集
	private int[] pageImages_help = new int[] { R.drawable.help_one, R.drawable.help_two, R.drawable.help_three};
	private ImageView[] dots;
	private int currentIndex;
	private int finishaction = FININSH_VIEWPAGE_FINISHACTIVITY;
	private boolean isJiaocheng = false;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// 沉浸式效果（系统状态栏将变的透明，界面从状态栏下方透过）
		XToolKits.setStatusBarTranslucent(this, true);

		super.onCreate(savedInstanceState);
		setContentView(R.layout.guide);
		
		ArrayList datas = IntentFactory.parseHelpActivityIntent(getIntent());
		finishaction = (Integer)datas.get(0);
		isJiaocheng = (Boolean)datas.get(1);
		
		initViews();
		initDots();
	}

	/**
	 * 本方法由父类的onCreate()调用，子类可在此方法中实现自已的UI显示逻辑。
	 */
	private void initViews()
	{
		mGestureDetector = new GestureDetector(this);   

		LayoutInflater inflater = LayoutInflater.from(this);

		views = new ArrayList<View>();

		vpAdapter = new ViewPagerAdapter(views, this);
		vpAdapter.finishAction = finishaction;
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);

		for (int i : (isJiaocheng ? pageImages_help : pageImages))
		{

			LinearLayout linearLayout = new LinearLayout(this);
			LinearLayout.LayoutParams mLayoutParams_2 = new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
					android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
			linearLayout.setLayoutParams(mLayoutParams_2);
			LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
					android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
			linearLayout.setOrientation(LinearLayout.HORIZONTAL);
			ImageView imageView = new ImageView(this);
			imageView.setLayoutParams(mLayoutParams);
			imageView.setImageResource(i);
			imageView.setScaleType(ScaleType.FIT_XY);
			linearLayout.addView(imageView);
			views.add(linearLayout);
		}
		views.add(inflater.inflate(R.layout.guide_lastloading, null));
//		if (isJiaocheng)
		{
			ImageView v = (ImageView) views.get(views.size() - 1).findViewById(R.id.img_bg);
			v.setImageResource(R.drawable.help_four);
			v.setScaleType(ScaleType.FIT_XY);
		}
		vp = (ViewPager) findViewById(R.id.viewpager);
		vp.setAdapter(vpAdapter);

		vp.setOnPageChangeListener(this);
		vp.setOnTouchListener(this);
	}

	public int getScreenWidth()
	{
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenWidthDip = dm.widthPixels;
		return screenWidthDip;
	}

	private void initDots()
	{
		LinearLayout ll = (LinearLayout) findViewById(R.id.ll);

		dots = new ImageView[views.size()];

		for (int i = 0; i < views.size(); i++)
		{
			ImageView img = new ImageView(this);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			params.gravity = Gravity.CENTER;
			img.setPadding(WidgetUtils.dip2px(this, 10), WidgetUtils.dip2px(this, 2), WidgetUtils.dip2px(this, 10), WidgetUtils.dip2px(this, 2));
			img.setClickable(true);
			img.setImageResource(i == 0 ? R.drawable.chatting_morefunc_pager_medium_indicator_selected_icon : R.drawable.chatting_morefunc_pager_medium_indicator_unselected_icon);
			img.setLayoutParams(params);
			ll.addView(img);
			dots[i] = img;
			dots[i].setEnabled(true);
		}

		currentIndex = 0;
		dots[currentIndex].setEnabled(false);
	}

	private void setCurrentDot(int position)
	{
		if (position < 0 || position > views.size() - 1 || currentIndex == position)
		{
			return;
		}

		dots[position].setImageResource(R.drawable.chatting_morefunc_pager_medium_indicator_selected_icon);
		dots[currentIndex].setImageResource(R.drawable.chatting_morefunc_pager_medium_indicator_unselected_icon);

		currentIndex = position;
	}

	@Override
	public void onPageScrollStateChanged(int position)
	{
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		return super.onTouchEvent(event);
	}

	@Override
	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
	{
		if(position == views.size())
		{
			if(!isJiaocheng)
			{
				ViewPagerAdapter.setGuided(HelpActivity.this);				
				startActivity(IntentFactory.createLoginIntent(this));
			}
			finish();
		}
	}

	@Override
	public void onPageSelected(int arg0)
	{
		setCurrentDot(arg0);
	}

	@Override
	public boolean onDown(MotionEvent e)
	{
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
	{
		// 参数解释：
		// e1：第1个ACTION_DOWN MotionEvent
		// e2：最后一个ACTION_MOVE MotionEvent
		// velocityX：X轴上的移动速度，像素/秒
		// velocityY：Y轴上的移动速度，像素/秒
		// 触发条件 ：
		// X轴的坐标位移大于FLING_MIN_DISTANCE，且移动速度大于FLING_MIN_VELOCITY个像素/秒

		final int FLING_MIN_DISTANCE = 50, FLING_MIN_VELOCITY = 0;

		//向左的手势
		if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY)
		{
			
			if(currentIndex == views.size() - 1)
			{
				if(!isJiaocheng)
				{
					ViewPagerAdapter.setGuided(HelpActivity.this);				
					startActivity(IntentFactory.createLoginIntent(this));
				}
				finish();
			}
		}
		//向右的手势
		else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY)
		{
			
		}
		return false;

	}

	@Override
	public void onLongPress(MotionEvent e)
	{
	}

	/* (non-Javadoc)
	 * @see android.view.GestureDetector.OnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent, float, float)
	 */
	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e)
	{
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e)
	{
		return false;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event)
	{
		return mGestureDetector.onTouchEvent(event);    
	}
	
	// Adapter实现类
	public static class ViewPagerAdapter extends PagerAdapter
	{
		public int finishAction;
		// 界面列表
		private List<View> views;
		public Activity activity;

		private static final String SHAREDPREFERENCES_NAME = "first_pref";

		public ViewPagerAdapter(List<View> views, Activity activity)
		{
			this.views = views;
			this.activity = activity;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2)
		{
			((ViewPager) arg0).removeView(views.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0)
		{
		}

		// 获得当前界面
		@Override
		public int getCount()
		{
			if (views != null)
			{
				return views.size();
			}
			return 0;
		}

		// 初始化arg1位置的界
		@Override
		public Object instantiateItem(View arg0, int arg1)
		{
			((ViewPager) arg0).addView(views.get(arg1), 0);
			if (arg1 == views.size() - 1)
			{
				Button mStartWeiboImageButton = (Button) arg0.findViewById(R.id.iv_start_weibo);
				mStartWeiboImageButton.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v)
					{
						if (finishAction == HelpActivity.FININSH_VIEWPAGE_GO_TAB_HOST)
						{
							// 设置已经引导
							setGuided(activity);
							goHome();
						}
						else if (finishAction == HelpActivity.FININSH_VIEWPAGE_FINISHACTIVITY)
						{
							activity.finish();
						}
					}
				});
			}
			return views.get(arg1);
		}

		private void goHome()
		{
			activity.startActivity(IntentFactory.createLoginIntent(activity));
			activity.finish();
		}

		/**
		 * 
		 * method desc：设置已经引导过了，下次启动不用再次引导
		 */
		public static void setGuided(Context context)
		{
			SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
			Editor editor = preferences.edit();
			// 存入数据
			editor.putBoolean("isFirstIn", false);
			// 提交修改
			editor.commit();
		}

		// 判断是否由对象生成界�?
		@Override
		public boolean isViewFromObject(View arg0, Object arg1)
		{
			return (arg0 == arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1)
		{
		}

		@Override
		public Parcelable saveState()
		{
			return null;
		}

		@Override
		public void startUpdate(View arg0)
		{
		}

	}
}
